/**
 * 错误代码对照表应用工具
 * by @author lms 2022.07.21
 */
package ms.core.common.utils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import ms.core.common.AppException;
import ms.core.common.consts.SysErr;
import ms.core.tool.Log4j2Tool;
import ms.core.tool.StrTool;
import ms.core.tool.StreamTool;

public class CodeTableUtils {
	private static String errTable = "/config/errortable.xml";
	private static Map<String, String> mapErr = null;

	static { init(); }

	/**
	 * 根据错误代码
	 * @param code
	 * @return
	 */
	public static String codeOfMsg(String code) {
		if (mapErr==null)
			throw new AppException(SysErr.CODE_FAILURE, "error table 'resources/config/errortable.xml' maybe not found.");
		
		String msg = mapErr.get(code);
		if (StrTool.isBlank(msg)) msg = "未定义错误信息";
		return msg;
	}

	/**
	 * 错误代码表文件初始化
	 * 
	 * @param fileName
	 */
	private static void init() {
		loadErrorTable();
	}
	
	private static void loadErrorTable(){
		try{
			InputStream in = StreamTool.loadFileToStream(CodeTableUtils.class, errTable);
			mapErr = new HashMap<>();
			SAXReader reader = new SAXReader();
			Document doc = reader.read(in);
			Element root = doc.getRootElement();
			List<Element> items = root.elements();
			for(Element item : items){
				mapErr.put(item.attributeValue("code"), item.attributeValue("value"));
			}
			in.close();
		} catch (Exception e) {
			Log4j2Tool.error(CodeTableUtils.class, "loadErrorTable:", e);
		}
	}
}
